
package com.android.fitnesscenter.server;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.android.fitnesscenter.utils.ConfigProperties;
import com.android.fitnesscenter.utils.Loger;
import com.android.fitnesscenter.utils.SharePrefsHelper;
import com.android.fitnesscenter.utils.ToastHelper;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

public class QueryService extends Service {

    private static final int INTERVAL_TIME = 10 * 1000;

    private Timer timer;
    private TimeHandler mTimeHandler;

    @Override
    public void onCreate() {
        super.onCreate();
        mTimeHandler = new TimeHandler();
        timer = new Timer();
        timer.schedule(new TimerQueryTask(), INTERVAL_TIME);
    }

    private class TimerQueryTask extends TimerTask {

        @Override
        public void run() {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    queryLastUpdate();
                }
            });
            mTimeHandler.sendEmptyMessage(0);
        }

    }

    @SuppressLint("HandlerLeak")
    private class TimeHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (timer != null) {
                timer.cancel();
            }
            timer = new Timer();
            timer.schedule(new TimerQueryTask(), INTERVAL_TIME);
        }

    }

    private SharePrefsHelper mSharePrefsHelper;

    protected String getToken() {
        if (mSharePrefsHelper == null) {
            mSharePrefsHelper = new SharePrefsHelper(ConfigProperties.SHARE_PREFS);
        }
        return mSharePrefsHelper.getString("token", "");
    }

    protected String getIMEI() {
        if (mSharePrefsHelper == null) {
            mSharePrefsHelper = new SharePrefsHelper(ConfigProperties.SHARE_PREFS);
        }
        String imei = mSharePrefsHelper.getString("imei", "");
        if (TextUtils.isEmpty(imei)) {
            TelephonyManager telManager = (TelephonyManager) QueryService.this.getSystemService(TELEPHONY_SERVICE);
            imei = telManager.getDeviceId();
            Loger.e("imei is " + imei + " mac is " + imei);
            mSharePrefsHelper.setString("imei", imei);
        }
        return imei;
    }

    protected void queryLastUpdate() {
        RequestParams params = new RequestParams();
        HttpUtils http = new HttpUtils();
        params.addBodyParameter("token", getToken());
        params.addBodyParameter("imei", getIMEI());
        String url = ConfigProperties.SERVICE_URL + "queryLastUpdate.do";
        Loger.e("url is " + url + " params is " + params);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                if (stringResponseInfo != null && !TextUtils.isEmpty(stringResponseInfo.result)) {
                    Loger.e("stringResponseInfo.result is " + stringResponseInfo.result);
                    try {
                        JSONObject jsonObject = new JSONObject(stringResponseInfo.result);
                        if (jsonObject != null) {
                            boolean success = jsonObject.getBoolean("success");
                            String msg = jsonObject.getString("message");
                            Loger.e("msg is " + msg);
                            if (success) {
                                if (jsonObject.has("model")) {
                                    JSONObject jsonObject2 = jsonObject.getJSONObject("model");
                                    String type = jsonObject2.getString("type");
                                    String username = jsonObject2.getString("username");
                                    ToastHelper.getInstance().showShortMsg(
                                            username + ConfigProperties.getType(type) + "成功");
                                }
                            } else {
                                QueryService.this.stopSelf();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {

                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Loger.e("msg:" + msg);
                QueryService.this.stopSelf();
            }
        });

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
